
<!DOCTYPE html>
<html lang="">


<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no">
  <meta name="theme-color" content="#202020">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <script src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" async></script>
  
  
    <meta name="keywords" content>
  

  
    <meta name="description" content="Go操作jwt">
  
  
  
  <link rel="icon" type="image/x-icon" href="/images/footer-logo.png">
  
  <title>Go操作jwt [ 51AIOps 专注于运维自动化  微信： kaipython ]</title>
  
    <!-- stylesheets list from config.yml -->
    
      <link rel="stylesheet" href="//cdn.bootcss.com/pure/1.0.0/pure-min.css">
    
      <link rel="stylesheet" href="/css/xoxo.css">
    
  
</head>


<body>
  <div class="nav-container">
    <nav class="home-menu pure-menu pure-menu-horizontal">
  <a class="pure-menu-heading" href="/">
    
    <span class="title" style="text-transform:none">51AIOps 专注于运维自动化  微信： kaipython</span>
  </a>

  <ul class="pure-menu-list clearfix">
      
          
            
              <li class="pure-menu-item"><a href="/" class="pure-menu-link">首页</a></li>
            
          
      
  </ul>
   
</nav>

  </div>

  <div class="container" id="content-outer">
    <div class="inner" id="content-inner" style='margin-left:-68px!important'>
      <div class="post-container">
  <article class="post" id="post">
    <header class="post-header text-center">
      <h1 class="title">
        Go操作jwt
      </h1>
      <span>
        
        <time class="time" datetime="2020-07-07T16:00:00.000Z">
        2020-07-08
      </time>
        
      </span>
      <span class="slash">/</span>
      <span class="post-meta">
      <span class="post-tags">
        
      </span>
    </span>
      <span class="slash">/</span>
      <span class="read">
      <span id="busuanzi_value_page_pv"></span> 点击
    </span>
      <span class="slash">/</span>
    </header>

    <div class="post-content">
      <p>JWT全称JSON Web Token是一种跨域认证解决方案，属于一个开放的标准，它规定了一种Token实现方式，目前多用于前后端分离项目和OAuth2.0业务场景下。</p>
<h2 id="什么是JWT？"><a href="#什么是JWT？" class="headerlink" title="什么是JWT？"></a>什么是JWT？</h2><p>JWT全称JSON Web Token是一种跨域认证解决方案，属于一个开放的标准，它规定了一种Token实现方式，目前多用于前后端分离项目和OAuth2.0业务场景下。</p>
<h2 id="为什么需要JWT？"><a href="#为什么需要JWT？" class="headerlink" title="为什么需要JWT？"></a>为什么需要JWT？</h2><p>在之前的一些web项目中，我们通常使用的是<code>Cookie-Session</code>模式实现用户认证。相关流程大致如下：</p>
<ol>
<li>用户在浏览器端填写用户名和密码，并发送给服务端</li>
<li>服务端对用户名和密码校验通过后会生成一份保存当前用户相关信息的session数据和一个与之对应的标识（通常称为session_id）</li>
<li>服务端返回响应时将上一步的session_id写入用户浏览器的Cookie</li>
<li>后续用户来自该浏览器的每次请求都会自动携带包含session_id的Cookie</li>
<li>服务端通过请求中的session_id就能找到之前保存的该用户那份session数据，从而获取该用户的相关信息。</li>
</ol>
<p>这种方案依赖于客户端（浏览器）保存Cookie，并且需要在服务端存储用户的session数据。</p>
<p>在移动互联网时代，我们的用户可能使用浏览器也可能使用APP来访问我们的服务，我们的web应用可能是前后端分开部署在不同的端口，有时候我们还需要支持第三方登录，这下<code>Cookie-Session</code>的模式就有些力不从心了。</p>
<p>JWT就是一种基于Token的轻量级认证模式，服务端认证通过后，会生成一个JSON对象，经过签名后得到一个Token（令牌）再发回给用户，用户后续请求只需要带上这个Token，服务端解密之后就能获取该用户的相关信息了。</p>
<p>想要连接JWT的原理，推荐大家阅读：<a href="https://www.ruanyifeng.com/blog/2018/07/json_web_token-tutorial.html" target="_blank" rel="noopener">阮一峰的JWT入门教程</a></p>
<h2 id="生成JWT和解析JWT"><a href="#生成JWT和解析JWT" class="headerlink" title="生成JWT和解析JWT"></a>生成JWT和解析JWT</h2><p>我们在这里直接使用<code>jwt-go</code>这个库来实现我们生成JWT和解析JWT的功能。</p>
<h3 id="定义需求"><a href="#定义需求" class="headerlink" title="定义需求"></a>定义需求</h3><p>我们需要定制自己的需求来决定JWT中保存哪些数据，比如我们规定在JWT中要存储<code>username</code>信息，那么我们就定义一个<code>MyClaims</code>结构体如下：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// MyClaims 自定义声明结构体并内嵌jwt.StandardClaims</span></span><br><span class="line"><span class="comment">// jwt包自带的jwt.StandardClaims只包含了官方字段</span></span><br><span class="line"><span class="comment">// 我们这里需要额外记录一个username字段，所以要自定义结构体</span></span><br><span class="line"><span class="comment">// 如果想要保存更多信息，都可以添加到这个结构体中</span></span><br><span class="line"><span class="keyword">type</span> MyClaims <span class="keyword">struct</span> &#123;</span><br><span class="line">	Username <span class="keyword">string</span> <span class="string">`json:"username"`</span></span><br><span class="line">	jwt.StandardClaims</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>然后我们定义JWT的过期时间，这里以2小时为例：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> TokenExpireDuration = time.Hour * <span class="number">2</span></span><br></pre></td></tr></table></figure>

<p>接下来还需要定义Secret：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> MySecret = []<span class="keyword">byte</span>(<span class="string">"夏天夏天悄悄过去"</span>)</span><br></pre></td></tr></table></figure>

<h3 id="生成JWT"><a href="#生成JWT" class="headerlink" title="生成JWT"></a>生成JWT</h3><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// GenToken 生成JWT</span></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">GenToken</span><span class="params">(username <span class="keyword">string</span>)</span> <span class="params">(<span class="keyword">string</span>, error)</span></span> &#123;</span><br><span class="line">	<span class="comment">// 创建一个我们自己的声明</span></span><br><span class="line">	c := MyClaims&#123;</span><br><span class="line">		<span class="string">"username"</span>, <span class="comment">// 自定义字段</span></span><br><span class="line">		jwt.StandardClaims&#123;</span><br><span class="line">			ExpiresAt: time.Now().Add(TokenExpireDuration).Unix(), <span class="comment">// 过期时间</span></span><br><span class="line">			Issuer:    <span class="string">"my-project"</span>,                               <span class="comment">// 签发人</span></span><br><span class="line">		&#125;,</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="comment">// 使用指定的签名方法创建签名对象</span></span><br><span class="line">	token := jwt.NewWithClaims(jwt.SigningMethodHS256, c)</span><br><span class="line">	<span class="comment">// 使用指定的secret签名并获得完整的编码后的字符串token</span></span><br><span class="line">	<span class="keyword">return</span> token.SignedString(MySecret)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="解析JWT"><a href="#解析JWT" class="headerlink" title="解析JWT"></a>解析JWT</h3><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// ParseToken 解析JWT</span></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">ParseToken</span><span class="params">(tokenString <span class="keyword">string</span>)</span> <span class="params">(*MyClaims, error)</span></span> &#123;</span><br><span class="line">	<span class="comment">// 解析token</span></span><br><span class="line">	token, err := jwt.ParseWithClaims(tokenString, &amp;MyClaims&#123;&#125;, <span class="function"><span class="keyword">func</span><span class="params">(token *jwt.Token)</span> <span class="params">(i <span class="keyword">interface</span>&#123;&#125;, err error)</span></span> &#123;</span><br><span class="line">		<span class="keyword">return</span> MySecret, <span class="literal">nil</span></span><br><span class="line">	&#125;)</span><br><span class="line">	<span class="keyword">if</span> err != <span class="literal">nil</span> &#123;</span><br><span class="line">		<span class="keyword">return</span> <span class="literal">nil</span>, err</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">if</span> claims, ok := token.Claims.(*MyClaims); ok &amp;&amp; token.Valid &#123; <span class="comment">// 校验token</span></span><br><span class="line">		<span class="keyword">return</span> claims, <span class="literal">nil</span></span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> <span class="literal">nil</span>, errors.New(<span class="string">"invalid token"</span>)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="在gin框架中使用JWT"><a href="#在gin框架中使用JWT" class="headerlink" title="在gin框架中使用JWT"></a>在gin框架中使用JWT</h2><p>首先我们注册一条路由<code>/auth</code>，对外提供获取Token的渠道：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">r.POST(<span class="string">"/auth"</span>, authHandler)</span><br></pre></td></tr></table></figure>

<p>我们的<code>authHandler</code>定义如下：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">authHandler</span><span class="params">(c *gin.Context)</span></span> &#123;</span><br><span class="line">	<span class="comment">// 用户发送用户名和密码过来</span></span><br><span class="line">	<span class="keyword">var</span> user UserInfo</span><br><span class="line">	err := c.ShouldBind(&amp;user)</span><br><span class="line">	<span class="keyword">if</span> err != <span class="literal">nil</span> &#123;</span><br><span class="line">		c.JSON(http.StatusOK, gin.H&#123;</span><br><span class="line">			<span class="string">"code"</span>: <span class="number">2001</span>,</span><br><span class="line">			<span class="string">"msg"</span>:  <span class="string">"无效的参数"</span>,</span><br><span class="line">		&#125;)</span><br><span class="line">		<span class="keyword">return</span></span><br><span class="line">	&#125;</span><br><span class="line">	<span class="comment">// 校验用户名和密码是否正确</span></span><br><span class="line">	<span class="keyword">if</span> user.Username == <span class="string">"szk"</span> &amp;&amp; user.Password == <span class="string">"szk123qwe"</span> &#123;</span><br><span class="line">		<span class="comment">// 生成Token</span></span><br><span class="line">		tokenString, _ := GenToken(user.Username)</span><br><span class="line">		c.JSON(http.StatusOK, gin.H&#123;</span><br><span class="line">			<span class="string">"code"</span>: <span class="number">2000</span>,</span><br><span class="line">			<span class="string">"msg"</span>:  <span class="string">"success"</span>,</span><br><span class="line">			<span class="string">"data"</span>: gin.H&#123;<span class="string">"token"</span>: tokenString&#125;,</span><br><span class="line">		&#125;)</span><br><span class="line">		<span class="keyword">return</span></span><br><span class="line">	&#125;</span><br><span class="line">	c.JSON(http.StatusOK, gin.H&#123;</span><br><span class="line">		<span class="string">"code"</span>: <span class="number">2002</span>,</span><br><span class="line">		<span class="string">"msg"</span>:  <span class="string">"鉴权失败"</span>,</span><br><span class="line">	&#125;)</span><br><span class="line">	<span class="keyword">return</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>用户通过上面的接口获取Token之后，后续就会携带着Token再来请求我们的其他接口，这个时候就需要对这些请求的Token进行校验操作了，很显然我们应该实现一个检验Token的中间件，具体实现如下：</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// JWTAuthMiddleware 基于JWT的认证中间件</span></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">JWTAuthMiddleware</span><span class="params">()</span> <span class="title">func</span><span class="params">(c *gin.Context)</span></span> &#123;</span><br><span class="line">	<span class="keyword">return</span> <span class="function"><span class="keyword">func</span><span class="params">(c *gin.Context)</span></span> &#123;</span><br><span class="line">		<span class="comment">// 客户端携带Token有三种方式 1.放在请求头 2.放在请求体 3.放在URI</span></span><br><span class="line">		<span class="comment">// 这里假设Token放在Header的Authorization中，并使用Bearer开头</span></span><br><span class="line">		<span class="comment">// 这里的具体实现方式要依据你的实际业务情况决定</span></span><br><span class="line">		authHeader := c.Request.Header.Get(<span class="string">"Authorization"</span>)</span><br><span class="line">		<span class="keyword">if</span> authHeader == <span class="string">""</span> &#123;</span><br><span class="line">			c.JSON(http.StatusOK, gin.H&#123;</span><br><span class="line">				<span class="string">"code"</span>: <span class="number">2003</span>,</span><br><span class="line">				<span class="string">"msg"</span>:  <span class="string">"请求头中auth为空"</span>,</span><br><span class="line">			&#125;)</span><br><span class="line">			c.Abort()</span><br><span class="line">			<span class="keyword">return</span></span><br><span class="line">		&#125;</span><br><span class="line">		<span class="comment">// 按空格分割</span></span><br><span class="line">		parts := strings.SplitN(authHeader, <span class="string">" "</span>, <span class="number">2</span>)</span><br><span class="line">		<span class="keyword">if</span> !(<span class="built_in">len</span>(parts) == <span class="number">2</span> &amp;&amp; parts[<span class="number">0</span>] == <span class="string">"Bearer"</span>) &#123;</span><br><span class="line">			c.JSON(http.StatusOK, gin.H&#123;</span><br><span class="line">				<span class="string">"code"</span>: <span class="number">2004</span>,</span><br><span class="line">				<span class="string">"msg"</span>:  <span class="string">"请求头中auth格式有误"</span>,</span><br><span class="line">			&#125;)</span><br><span class="line">			c.Abort()</span><br><span class="line">			<span class="keyword">return</span></span><br><span class="line">		&#125;</span><br><span class="line">		<span class="comment">// parts[1]是获取到的tokenString，我们使用之前定义好的解析JWT的函数来解析它</span></span><br><span class="line">		mc, err := ParseToken(parts[<span class="number">1</span>])</span><br><span class="line">		<span class="keyword">if</span> err != <span class="literal">nil</span> &#123;</span><br><span class="line">			c.JSON(http.StatusOK, gin.H&#123;</span><br><span class="line">				<span class="string">"code"</span>: <span class="number">2005</span>,</span><br><span class="line">				<span class="string">"msg"</span>:  <span class="string">"无效的Token"</span>,</span><br><span class="line">			&#125;)</span><br><span class="line">			c.Abort()</span><br><span class="line">			<span class="keyword">return</span></span><br><span class="line">		&#125;</span><br><span class="line">		<span class="comment">// 将当前请求的username信息保存到请求的上下文c上</span></span><br><span class="line">		c.Set(<span class="string">"username"</span>, mc.Username)</span><br><span class="line">		c.Next() <span class="comment">// 后续的处理函数可以用过c.Get("username")来获取当前请求的用户信息</span></span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>注册一个<code>/home</code>路由，发个请求验证一下吧。</p>
<figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">r.GET(<span class="string">"/home"</span>, JWTAuthMiddleware(), homeHandler)</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">homeHandler</span><span class="params">(c *gin.Context)</span></span> &#123;</span><br><span class="line">	username := c.MustGet(<span class="string">"username"</span>).(<span class="keyword">string</span>)</span><br><span class="line">	c.JSON(http.StatusOK, gin.H&#123;</span><br><span class="line">		<span class="string">"code"</span>: <span class="number">2000</span>,</span><br><span class="line">		<span class="string">"msg"</span>:  <span class="string">"success"</span>,</span><br><span class="line">		<span class="string">"data"</span>: gin.H&#123;<span class="string">"username"</span>: username&#125;,</span><br><span class="line">	&#125;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>如果不想自己实现上述功能，你也可以使用Github上别人封装好的包，比如<a href="https://github.com/appleboy/gin-jwt。" target="_blank" rel="noopener">https://github.com/appleboy/gin-jwt。</a></p>

    </div>

  </article>
  <div class="toc-container">
    
  <div id="toc" class="toc-article">
    <strong class="toc-title">目录</strong>
    <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#什么是JWT？"><span class="toc-text">什么是JWT？</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#为什么需要JWT？"><span class="toc-text">为什么需要JWT？</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#生成JWT和解析JWT"><span class="toc-text">生成JWT和解析JWT</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#定义需求"><span class="toc-text">定义需求</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#生成JWT"><span class="toc-text">生成JWT</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#解析JWT"><span class="toc-text">解析JWT</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#在gin框架中使用JWT"><span class="toc-text">在gin框架中使用JWT</span></a></li></ol>
  </div>


  </div>
</div>
<script type="text/javascript" src="//rf.revolvermaps.com/0/0/8.js?i=5sr5du46f27&amp;m=0&amp;c=ff0000&amp;cr1=ffffff&amp;f=arial&amp;l=33" async="async"></script>
<div class="copyright">
    <span>本作品采用</span>
    <a href="https://creativecommons.org/licenses/by/4.0/">知识共享署名 4.0 国际许可协议</a>
    <span>进行许可。 转载时请注明原文链接。</span>
</div>


  
    <div class="post-nav" style="margin-left:-168px;">
      <div class="post-nav-item post-nav-next">
        
          <span>〈 </span>
          <a href="/2020/06/09/稳定性实践：容量规划之压测系统建设/" rel="next" title="稳定性实践：容量规划之压测系统建设">
          稳定性实践：容量规划之压测系统建设
          </a>
        
      </div>
  
      <div class="post-nav-item post-nav-prev">
          
          <a href="/2020/07/29/Go语言之map的使用/" rel="prev" title="Go语言之map的使用">
            Go语言之map的使用
          </a>
          <span>〉</span>
        
      </div>
    </div>
  


	
	<div style="width:109%; margin-left:-144px" id="lv-container" data-id="city" data-uid="MTAyMC80OTg5NS8yNjM4Ng==">
	<script type="text/javascript">
   	   (function(d, s) {
       		var j, e = d.getElementsByTagName(s)[0];

       		if (typeof LivereTower === 'function') { return; }

       		j = d.createElement(s);
       		j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
       		j.async = true;

       		e.parentNode.insertBefore(j, e);
   	   })(document, 'script');
	</script>
	<noscript> 为正常使用来必力评论功能请激活JavaScript</noscript>
        </div>
	



    </div>

    

  </div>
  <footer class="footer text-center">
    <div id="bottom-inner">
        <a class="bottom-item" href target="_blank">GitHub</a> |
        <a class="bottom-item" href>友情链接</a> |
        <a class="bottom-item" href="https://hexo.io" target="_blank">Powered by hexo</a> |
        <a class="bottom-item" href="https://github.com/fooying/hexo-theme-xoxo-plus" target="_blank">Theme xoxo-plus</a> |
        <a class="bottom-item" href="/atom.xml">订阅</a>
    </div>
</footer>

  

<script>
  (function(window, document, undefined) {

    var timer = null;

    function returnTop() {
      cancelAnimationFrame(timer);
      timer = requestAnimationFrame(function fn() {
        var oTop = document.body.scrollTop || document.documentElement.scrollTop;
        if (oTop > 0) {
          document.body.scrollTop = document.documentElement.scrollTop = oTop - 50;
          timer = requestAnimationFrame(fn);
        } else {
          cancelAnimationFrame(timer);
        }
      });
    }

    var hearts = [];
    window.requestAnimationFrame = (function() {
      return window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.oRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        function(callback) {
          setTimeout(callback, 1000 / 60);
        }
    })();
    init();

    function init() {
      css(".heart{z-index:9999;width: 10px;height: 10px;position: fixed;background: #f00;transform: rotate(45deg);-webkit-transform: rotate(45deg);-moz-transform: rotate(45deg);}.heart:after,.heart:before{content: '';width: inherit;height: inherit;background: inherit;border-radius: 50%;-webkit-border-radius: 50%;-moz-border-radius: 50%;position: absolute;}.heart:after{top: -5px;}.heart:before{left: -5px;}");
      attachEvent();
      gameloop();
      addMenuEvent();
    }

    function gameloop() {
      for (var i = 0; i < hearts.length; i++) {
        if (hearts[i].alpha <= 0) {
          document.body.removeChild(hearts[i].el);
          hearts.splice(i, 1);
          continue;
        }
        hearts[i].y--;
        hearts[i].scale += 0.004;
        hearts[i].alpha -= 0.013;
        hearts[i].el.style.cssText = "left:" + hearts[i].x + "px;top:" + hearts[i].y + "px;opacity:" + hearts[i].alpha + ";transform:scale(" + hearts[i].scale + "," + hearts[i].scale + ") rotate(45deg);background:" + hearts[i].color;
      }
      requestAnimationFrame(gameloop);
    }

    /**
     * 给logo设置点击事件
     * 
     * - 回到顶部
     * - 出现爱心
     */
    function attachEvent() {
      var old = typeof window.onclick === "function" && window.onclick;
      var logo = document.getElementById("logo");
      if (logo) {
        logo.onclick = function(event) {
          returnTop();
          old && old();
          createHeart(event);
        }
      }
      
    }

    function createHeart(event) {
      var d = document.createElement("div");
      d.className = "heart";
      hearts.push({
        el: d,
        x: event.clientX - 5,
        y: event.clientY - 5,
        scale: 1,
        alpha: 1,
        color: randomColor()
      });
      document.body.appendChild(d);
    }

    function css(css) {
      var style = document.createElement("style");
      style.type = "text/css";
      try {
        style.appendChild(document.createTextNode(css));
      } catch (ex) {
        style.styleSheet.cssText = css;
      }
      document.getElementsByTagName('head')[0].appendChild(style);
    }

    function randomColor() {
      // return "rgb(" + (~~(Math.random() * 255)) + "," + (~~(Math.random() * 255)) + "," + (~~(Math.random() * 255)) + ")";
      return "#F44336";
    }

    function addMenuEvent() {
      var menu = document.getElementById('menu-main-post');
      if (menu) {
        var toc = document.getElementById('toc');
        if (toc) {
          menu.onclick = function() {
            if (toc) {
              if (toc.style.display == 'block') {
                toc.style.display = 'none';
              } else {
                toc.style.display = 'block';
              }
            }
          };
        } else {
          menu.style.display = 'none';
        }
      }
    }

  })(window, document);
</script>

  



  

</body>
</html>
